﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using ScheduleParserWorkerRole;

namespace RecorderWorkerRole
{
    public class DownloadersRegistry
    {
        private readonly Dictionary<long, Downloader> _downloaders = new Dictionary<long, Downloader>();

        public void Remove(List<long> iIds)
        {
            foreach (var iterKey in iIds)
            {
                _downloaders.Remove(iterKey);
            }
        }

        public Downloader GetDownloader(schedule iterShow)
        {
            if (_downloaders.ContainsKey(iterShow.Id))
            {
                return _downloaders[iterShow.Id];
            }
            else
            {
                return (_downloaders[iterShow.Id] = new Downloader(iterShow));
            }
        }

        public TimeSpan GetInactivityTimeout()
        {
            var activeDownloaders = GetActiveDownloads().ToList();
            if (activeDownloaders.Any())
            {
                var nextWakeUp = activeDownloaders.
                    Min(item => item.StateExpirationTime);
                if (nextWakeUp > DateTime.UtcNow)
                {
                    return nextWakeUp - DateTime.UtcNow;
                }
                else
                {
                    //Sometimes, we run out of resources, and some downloads become expired even before the cycle ends. 
                    //Anyway, sleep one second, and reprocess. In some congestion scenarios, sleeping for 5 seconds would be even
                    //more preferrable
                    return TimeSpan.FromSeconds(1);
                }
            }
            return TimeSpan.FromMinutes(5);
        }

        public bool Exists(long key)
        {
            return _downloaders.ContainsKey(key);
        }
        
        public IEnumerable<Downloader> GetActiveDownloads()
        {
            return _downloaders.
                Where(item => item.Value.State != Downloader.EDownloadStates.DownloadFinishedForgetMe).
                Select(item=>item.Value);
        }
    }
}